import React, { useEffect, useState, useRef } from 'react'
import { Button, Statistic, Modal, Layout, Select, Cascader, Avatar, message, Descriptions, Input, Upload, Row, Popover, Col, Typography, Divider } from 'antd';
import { UploadOutlined, DeleteTwoTone, PlusSquareTwoTone, EditTwoTone } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom'
import axios from 'axios';
import { screenHeight, screenWidth } from '../../../../Constants/index'
import myprovinceData from '../../../../js/provinceData';
import { Column } from '@ant-design/plots';
const { Option } = Select;
const { Title } = Typography;
const provinceData = myprovinceData;
export default function Index() {
  let editUserInfo = {}
  const navigate = useNavigate()
  const [loginUser, setLoginUser] = useState(JSON.parse(localStorage.getItem("loginUser")))
  const { Content, } = Layout;
  const [editvisible, seteditVisible] = useState(false);
  const [delModal, setdelModal] = useState(false);
  const [myId, setMyId] = useState(loginUser.id);

  const pwdRef = useRef();
  const nameRef = useRef();
  const addressRef = useRef();
  const phoneRef = useRef();
  const emailRef = useRef();

  const [myChangeInfoCount, setmyChangeInfoCount] = useState(0)
  const [myLikeCount, setmyLikeCount] = useState(0)
  const [changeTimeCount, setchangeTimeCount] = useState(0)
  const [doCount, setdoCount] = useState(0)
  const [giftCount, setgiftCount] = useState(0)
  useEffect(async () => {
    message.destroy();

    const resp = await axios.get("http://localhost:8080/userData?userid=" + myId)
    console.log("用户数据", resp.data.userdata);
    setmyChangeInfoCount(resp.data.userdata["物品数量"]);
    setmyLikeCount(resp.data.userdata["收藏数量"]);
    setchangeTimeCount(resp.data.userdata["交换次数"]);
    setdoCount(resp.data.userdata["捐赠次数"]);
    setgiftCount(resp.data.userdata["兑换礼物"]);
    return () => {
      //销毁组件时
      console.log('menu-destroy');
    };
  }, []);

  const data = [
    {
      type: '我的物品',
      sales: myChangeInfoCount,
    },
    {
      type: '我的收藏',
      sales: myLikeCount,
    },
    {
      type: '交换次数',
      sales: changeTimeCount,
    },
    {
      type: '捐赠次数',
      sales: doCount,
    },
    {
      type: '兑换礼物',
      sales: giftCount,
    },
  ];
  const config = {
    data,
    xField: 'type',
    yField: 'sales',
    label: {
      position: 'middle',
      style: {
        fill: '#FFFFFF',
        opacity: 0.6,
      },
    },
    xAxis: {
      label: {
        autoHide: true,
        autoRotate: false,
      },
    },
    meta: {
      type: {
        alias: '类别',
      },
      sales: {
        alias: '数量',
      },
    },
  };

  const showModal = () => {
    seteditVisible(true);
    pwdRef.current.state.value = null;
    nameRef.current.state.value = null;
    addressRef.current.state.value = null;
    phoneRef.current.state.value = null;
    emailRef.current.state.value = null;
  };

  const handleOk = () => {
    const pwdReg = /^[a-zA-Z0-9]{6,18}$/;
    const emailreg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    const phonereg = /^1[34578]\d{9}$/;
    editUserInfo.password = pwdRef.current.state.value || null;
    editUserInfo.nickname = nameRef.current.state.value || null;
    editUserInfo.address = addressRef.current.state.value || null;
    editUserInfo.phone = phoneRef.current.state.value || null;
    editUserInfo.email = emailRef.current.state.value || null;
    editUserInfo.id = myId;
    if (editUserInfo.password != null) {
      if (!pwdReg.test(editUserInfo.password)) {
        message.error("密码为6-18位包含数字字母的组合!")
        return
      }

    }
    if (editUserInfo.nickname != null) {
      if (editUserInfo.nickname.length > 20) {
        message.error("昵称不能大于20个字符!")
        return
      }
    }
    if (editUserInfo.email != null) {
      if (!emailreg.test(editUserInfo.email)) {
        message.error("邮箱格式错误!")
        return
      }
    }
    if (editUserInfo.phone != null) {
      if (!phonereg.test(editUserInfo.phone)) {
        message.error("手机号格式错误!")
        return
      }
    }


    axios.post("http://localhost:8080/editUser", editUserInfo).then(resp => {
      if (resp.data.state === "0") {
        message.success(resp.data.message, 1)
        seteditVisible(false);
        setTimeout(() => {
          window.location.reload();
        }, 500);

      } else {
        message.error(resp.data.message, 1)
        seteditVisible(false);
      }

    }).catch(err => {
      message.error("请求超时!", 1);
      seteditVisible(false);
    })
  };

  const genderSelect = (value) => {
    editUserInfo.gender = value;
  }

  const citySelect = (value) => {
    editUserInfo.city = value;
  }

  const handleCancel = () => {
    seteditVisible(false);
    editUserInfo = {}
  };
  const deleteMe = () => {
    setdelModal(true)
  }
  const delMeOk = () => {
    axios.post("http://localhost:8080/deleteUser?id=" + myId).then(resp => {
      if (resp.data.state === "0") {
        message.success(resp.data.message, 1);
        setdelModal(false)
        localStorage.clear()
        setTimeout(() => {
          navigate('/loginAndRegister/*')
        }, 300);

      } else {
        message.error(resp.data.message, 1)
        setdelModal(false)
      }
    }).catch(err => {
      message.error("网络超时!", 1)
      setdelModal(false)
    })
  }
  const delMeCancel = () => {
    setdelModal(false)
  }
  const beforeUpload = (file) => {
    console.log(file.size);
    if (file.size > (2097152)) {
      console.log("图片超过2M");
      message.error(`图片不得超过2M`);
      return Upload.LIST_IGNORE;
    } else {
      return true;
    }
  }
  const photoupdate = (info) => {

    if (info.file.status === 'done') {
      message.success(`${info.file.name}图片上传成功`);
      setTimeout(() => {
        window.location.reload()
      }, 500);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 图片上传失败`);
    }

  }
  return (

    <Content style={{ padding: 15, backgroundColor: '#FFF' }} className="animate__animated animate__fadeIn">
      <Row >
        <Col>
          <Title level={3}>个人资料</Title>
        </Col>

      </Row>

      <Row justify="center">
        <Col>
          <Popover placement="topLeft" content={'点击修改头像'}>
            <Upload maxCount={1} action={`http://localhost:8080/saveUserHead?id=${myId}`} beforeUpload={beforeUpload} onChange={photoupdate}>
              <Avatar src={`http://localhost:8080/getUserHead?id=${myId}`} alt='用户头像' size={100} />
            </Upload>
          </Popover>
        </Col>
      </Row>
      <Row justify="center" style={{ marginTop: '0.3REM' }}>
        <Col>
          <Descriptions bordered column={{ xxl: 4, xl: 3, lg: 3, md: 3, sm: 2, xs: 1 }} size="middle " >
            <Descriptions.Item label="昵称">{loginUser.nickname}</Descriptions.Item>

            <Descriptions.Item label="性别">{loginUser.gender == "0" ? "男" : loginUser.gender == "1" ? "女" : "保密"}</Descriptions.Item>
            <Descriptions.Item label="城市">{loginUser.city}</Descriptions.Item>
            <Descriptions.Item label="累计积分">{loginUser.point}</Descriptions.Item>
            <Descriptions.Item label="可用积分">{loginUser.shoppoint}</Descriptions.Item>
            <Descriptions.Item label="地址" >{loginUser.address}</Descriptions.Item>
            <Descriptions.Item label="邮箱">{loginUser.email}</Descriptions.Item>
            <Descriptions.Item label="手机">{loginUser.phone}</Descriptions.Item>
            <Descriptions.Item label="操作">

              <Row justify="space-around" gutter={8}>
                <Col >
                  <Button type="primary" danger onClick={deleteMe}>永久注销</Button>
                </Col>
                <Col>
                  <Button type="primary" onClick={showModal}>修改信息</Button>
                </Col>
              </Row>
            </Descriptions.Item>
          </Descriptions>
        </Col>
      </Row>

      <Row>
        <Col>
          <Title level={3}>个人数据</Title>
        </Col>

      </Row>
      <Column {...config} />


      <Modal
        title="编辑资料"
        visible={editvisible}
        onOk={handleOk}
        onCancel={handleCancel}
        centered={true}
      >
        <Row justify="center">
          <Col>
            <Input type={"password"} placeholder="密码" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={pwdRef} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Input placeholder="昵称" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={nameRef} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Input placeholder="地址" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={addressRef} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Input placeholder="手机" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={phoneRef} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Input placeholder="邮箱" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={emailRef} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Cascader placeholder={"城市"} style={{ width: '1.7REM', marginTop: '0.03REM' }} onChange={citySelect} options={provinceData} defaultValue={''} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Select placeholder="性别" defaultValue='' onSelect={genderSelect} style={{ width: '1.7REM', marginTop: '0.03REM' }}>
              <Option value="0">男</Option>
              <Option value="1">女</Option>
              <Option value="2">保密</Option>
            </Select>
          </Col>
        </Row>
      </Modal>

      <Modal
        title="警告！"
        visible={delModal}
        onOk={delMeOk}
        onCancel={delMeCancel}
        width={'35%'}
        centered={true}
      >
        <Row>
          <Col>
            本次操作后将永久删除该用户信息
          </Col>
        </Row>
        <Row>
          <Col>
            若想再次使用本系统,请重新注册!
          </Col>
        </Row>
      </Modal>

    </Content>
  )

}
